from flask import Flask,render_template,request,Response,redirect,url_for
import pyautogui as pag
from getScreenshot import get_frame



##########超参数（使用前修改）##########
if_screenshot = 'true' #不需要传截屏时设为'false',需要时设为'true'
##########超参数##########



app = Flask(__name__)

"""
pyautogui.position() # 获取鼠标当前位置

# 绝对位置移动，移动至屏幕正中心，鼠标移动过渡时间duration设为1秒
pyautogui.moveTo(sizex/2,sizey/2,duration=1)

# 相对位置移动，向右100、向上200，鼠标移动过渡时间duration设为0.5秒
pyautogui.moveRel(100, -200, duration=0.5)
"""
def gen():
	while True:
		frame = get_frame()
		yield (b'--frame\r\n'
				b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')



@app.route('/ctrl',methods=['get','post'])
def ctrl():
	global if_screenshot
	if request.method == 'GET':
		return render_template('ctrl_page.html',screenshot=if_screenshot)
	elif request.method == 'POST':
		if request.form.get('key'):
			data = request.form.get('key')
			pag.press(data)

		elif request.form.get('mouse'):
			data = request.form.get('mouse')
			if data:
				if data=='up':
					pag.moveRel(0,-10)
				elif data=='down':
					pag.moveRel(0,10)
				elif data=='left':
					pag.moveRel(-10,0)
				elif data=='right':
					pag.moveRel(10,0)
				elif data=='click':
					pag.click()
				elif data=='r-click':
					pag.rightClick()
				elif data=='db-click':
					pag.doubleClick()
				elif 'x-' in data:
					x = int(data.split('-')[1])
					y = int(data.split('-')[3])
					pag.moveTo(x,y)
					pag.click()

		elif request.form.get('typing'):
			data = request.form.get('typing')
			pag.typewrite(data)

		elif request.form.get('hotkey'):
			data = request.form.get('hotkey')
			pag.hotkey(*(data.split(' ')))

		elif request.form.get('op'):
			data = request.form.get('op')
			if data=='fullscr':
				pag.hotkey('windows','up')
				sizex = pag.size().width
				sizey = pag.size().height
				pag.moveTo(sizex/2,sizey/2)
				pag.doubleClick()
		print(data)
		return '200'

@app.route('/ctrl/screenshot')
def ss():
	return Response(gen(),
		mimetype='multipart/x-mixed-replace; boundary=frame')
	# pag.screenshot('ss.png')
	# img = open('ss.png','rb')
	# resp = Response(img,mimetype='image/png')
	# return resp

if __name__ == '__main__':
	app.run('0.0.0.0',8080,debug=True)
	app.add_url_rule('/favicon.ico',redirect_to=url_for('static',filename='img/favicon.ico'))














